//
//  testViewController.swift
//  swfitTest
//
//  Created by hncy on 2022/7/4.
//

import Foundation
import Alamofire
import UIKit
import WebKit

class DetailViewController:ViewController {
    struct BaseEmptyParameter: Encodable {
        
    }
    
    var item:HomeModel?
    var id:String?
    
    lazy var webView:WKWebView = {
        let config = WKWebViewConfiguration()
        // web内容处理池
        config.processPool = WKProcessPool()
        // 视屏内联播放
        config.allowsInlineMediaPlayback = true
        //设置webview允许跨域
        config.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        config.setValue(true, forKey: "allowUniversalAccessFromFileURLs")
        
        
        let webView = WKWebView(frame: UIScreen.main.bounds,configuration: config)
        webView.backgroundColor = UIColor.white
        return webView
    }()
    
    required init(id:String) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
    }
   
     
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title="详情"
        self.view.backgroundColor = UIColor.white 
        self.view.addSubview(webView)
        
        getDetail()
        
    
    }
    func getDetail() {
        AF.request("https://cnodejs.org/api/v1/topic/"+(self.id ?? ""), method: .get, parameters: BaseEmptyParameter(), encoder: URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(), destination: .methodDependent), headers: nil, interceptor: nil, requestModifier: nil).response { [self] response in
 
            // data to jsonstring
            let jsonString = String(bytes: response.data!, encoding: String.Encoding.utf8)
             
            
            print(jsonString)
            if let model =  HomeModel.deserialize(from: jsonString, designatedPath: "data") {

                self.item = (model as! HomeModel)
                webView.loadHTMLString(self.item?.content ?? "", baseURL: nil)
               
            }
        }
    }
    
}
